<?php

class Player extends Model {
  const ID_XPATH = "./@id";
  const TYPE_XPATH = "./@type";
  const NAME_XPATH = "./name[1]";
  const AGE_XPATH = "./age[1]";
  const SKILLS_XPATH = "./skills[1]/skill";
  const PREFERREDFOOT_XPATH = "./preferred_foot[1]";
  const FORM_XPATH = "./form[1]";
  const MATCHREADINESS_XPATH = "./match_readiness[1]";
  const EXPERIENCE_XPATH = "./experience[1]";
  const LOYALTY_XPATH = "./loyalty[1]";
  const TRAINING_XPATH = "./training[1]";
  const COMMITMENT_XPATH = "./commitment[1]";
  const CHOICES_XPATH = "./choices[1]/choice";
  const SALARY_XPATH = "./salary[1]";
  const PURCHASEPRICE_XPATH = "./purchase_price[1]";
  const JOINDATE_XPATH = "./join_date[1]";
  const NATION_XPATH = "./nation[1]";
  const HOMECLUBID_XPATH = "./home_club[1]/@id";
  const PERSONALITIES_XPATH ="./personalities[1]/personality";
  const SPECIALABILITIES_XPATH ="./special_abilities[1]/special_ability";
  const REVEALSKILLS_XPATH ="./reveal_skills[1]/@active";
  const UNDEREVALUATION_XPATH ="./under_evaluation[1]/@active";
  const NATIONALTEAM_XPATH ="./national_team[1]";
  const NATIONALTEAMPROSPECT_XPATH ="./national_team_prospect[1]";
  const MATCHES_XPATH = "./matches[1]";

  private $form;
  private $matchReadiness;
  private $experience;
  private $loyalty;
  private $training;
  private $commitment;
  private $choices;
  private $salary;
  private $purchasePrice;
  private $joinDate;
  private $nation;
  private $homeClubId;
  private $personalities;
  private $specialAbilities;
  private $revealSkills;
  private $underEvaluation;
  private $nationalTeam;
  private $nationalTeamProspect;
  private $matches;
  private $isDeleted;

  public function __construct() {
    parent::Model();
  }

//  public function loadFromNode(DOMElement $docNode) {
//    $doc = $docNode->ownerDocument;
//
//    $xPath = new DOMXPath($doc);
//
//    $qResult = $xPath->query(Player::ID_XPATH,$docNode);
//    $this->id = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::TYPE_XPATH,$docNode);
//    $this->type = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::NAME_XPATH,$docNode);
//    $this->name->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::AGE_XPATH,$docNode);
//    $this->age->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::SKILLS_XPATH,$docNode);
//    foreach ($qResult as $result) {
//      $skill = new PlayerSkill($this->db);
//      $skill->loadFromNode($result);
//      array_push($this->skills, $skill);
//    }
//
//    $qResult = $xPath->query(Player::PREFERREDFOOT_XPATH,$docNode);
//    $this->preferredFoot = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::FORM_XPATH,$docNode);
//    $this->form->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::MATCHREADINESS_XPATH,$docNode);
//    $this->matchReadiness->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::EXPERIENCE_XPATH,$docNode);
//    $this->experience = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::LOYALTY_XPATH,$docNode);
//    $this->loyalty = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::TRAINING_XPATH,$docNode);
//    $this->training->loadFromNode($qResult->item(0));
//
//    if ($this->type=='outfielder') {
//      $qResult = $xPath->query(Player::COMMITMENT_XPATH,$docNode);
//      $this->commitment = $qResult->item(0)->nodeValue;
//    }
//
//    $qResult = $xPath->query(Player::CHOICES_XPATH,$docNode);
//    foreach ($qResult as $result) {
//      $choice = new PlayerChoise($this->db);
//      $choice->loadFromNode($result);
//      array_push($this->choices, $choice);
//    }
//
//    $qResult = $xPath->query(Player::SALARY_XPATH,$docNode);
//    $this->salary->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::PURCHASEPRICE_XPATH,$docNode);
//    $this->purchasePrice = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::JOINDATE_XPATH,$docNode);
//    $this->joinDate = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::NATION_XPATH,$docNode);
//    $this->nation = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::HOMECLUBID_XPATH,$docNode);
//    $this->homeClubId = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::PERSONALITIES_XPATH,$docNode);
//    foreach ($qResult as $result) {
//      array_push($this->personalities, $result->nodeValue);
//    }
//
//    $qResult = $xPath->query(Player::SPECIALABILITIES_XPATH,$docNode);
//    foreach ($qResult as $result) {
//      array_push($this->specialAbilities, $result->nodeValue);
//    }
//
//    $qResult = $xPath->query(Player::REVEALSKILLS_XPATH,$docNode);
//    $this->revealSkills = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::UNDEREVALUATION_XPATH,$docNode);
//    $this->underEvaluation = $qResult->item(0)->nodeValue;
//
//    $qResult = $xPath->query(Player::NATIONALTEAM_XPATH,$docNode);
//    $this->nationalTeam->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::NATIONALTEAMPROSPECT_XPATH,$docNode);
//    $this->nationalTeamProspect->loadFromNode($qResult->item(0));
//
//    $qResult = $xPath->query(Player::MATCHES_XPATH,$docNode);
//    $this->matches->loadFromNode($qResult->item(0));
//
//    $this->isDeleted = false;
//
//    log_message('info','Player('.$this->id.') class was created.');
//  }

  public function insertNewToDB($clubId) {
    $nameId = $this->name->insertNewToDB($this->id);
    $ageId = $this->age->insertNewToDB($this->id);

    $skillIds = '';
    foreach ($this->skills as $skill) {
      $skillIds .= $skill->insertNewToDB($this->id). ',';
    }
    $skillIds = substr($skillIds, 0, -1);

    $formId = $this->form->insertNewToDB($this->id);
    $matchReadinessId = $this->matchReadiness->insertNewToDB($this->id);

    $this->db->set('playerId',$this->id);
    $this->db->set('experience',$this->experience);
    $query = $this->db->insert('playerexperience');
    $experienceId = $this->db->insert_id();

    $this->db->set('playerId',$this->id);
    $this->db->set('loyalty',$this->loyalty);
    $query = $this->db->insert('playerloyalty');
    $loyaltyId = $this->db->insert_id();

    $trainingId = $this->training->insertNewToDB($this->id);

    $commitmentId = null;
    if ($this->type=='outfielder') {
      $this->db->set('playerId',$this->id);
      $this->db->set('commitment',$this->commitment);
      $query = $this->db->insert('playercommitment');
      $commitmentId = $this->db->insert_id();
    }

    $choiceIds = '';
    foreach ($this->choices as $choice) {
      $choiceIds .= $choice->insertNewToDB($this->id) . ',';
    }
    $choiceIds = substr($choiceIds, 0, -1);

    $salaryId = $this->salary->insertNewToDB($this->id);

    $personalities = "";
    foreach ($this->personalities as $personality) {
      $personalities .= $personality.',';
    }
    $personalities = substr($personalities, 0, -1);

    $specialAbilities = '';
    foreach ($this->specialAbilities as $specialAbility) {
      $specialAbilities .= $specialAbility.',';
    }
    $specialAbilities = substr($specialAbilities, 0, -1);

    $this->db->set('playerId',$this->id);
    $this->db->set('revealSkills',$this->revealSkills);
    $query = $this->db->insert('playerrevealskills');
    $revealId = $this->db->insert_id();

    $this->db->set('playerId',$this->id);
    $this->db->set('underEvaluation',$this->underEvaluation);
    $query = $this->db->insert('playerunderevaluation');
    $underEvalId = $this->db->insert_id();

    $nationalTeamId = $this->nationalTeam->insertNewToDB($this->id);
    $nationalTeamProspectId = $this->nationalTeamProspect->insertNewToDB($this->id);
    $matchesId = $this->matches->insertNewToDB($this->id);

    $this->db->set('id',$this->id);
    $this->db->set('clubId',$clubId);
    $this->db->set('type',$this->type);
    $this->db->set('nameId',$nameId);
    $this->db->set('ageId',$ageId);
    $this->db->set('skillsIds',$skillIds);
    $this->db->set('preferredFoot',$this->preferredFoot);
    $this->db->set('formId',$formId);
    $this->db->set('matchReadinessId',$matchReadinessId);
    $this->db->set('experienceId',$experienceId);
    $this->db->set('loyaltyId',$loyaltyId);
    $this->db->set('trainingId',$trainingId);
    $this->db->set('commitmentId',$commitmentId);
    $this->db->set('choiceIds',$choiceIds);
    $this->db->set('salaryId',$salaryId);
    $this->db->set('purchasePrice',$this->purchasePrice);
    $this->db->set('joinDate',$this->joinDate);
    $this->db->set('nation',$this->nation);
    $this->db->set('joinDate',$this->joinDate);
    $this->db->set('homeClubId',$this->homeClubId);
    $this->db->set('personalities',$personalities);
    $this->db->set('specialAbilities',$specialAbilities);
    $this->db->set('revealSkillsId',$revealId);
    $this->db->set('underEvaluationId',$underEvalId);
    $this->db->set('nationalTeamId',$nationalTeamId);
    $this->db->set('nationalTeamProspectId',$nationalTeamProspectId);
    $this->db->set('matchesId',$matchesId);
    $this->db->set('isDeleted',$this->isDeleted);
    $query = $this->db->insert('player');

    if (!$query) {
      log_message('error', 'Error during player inserttion to database!');
    } else {
      log_message('error', 'New player record ('.$this->id.') was inserted to the database!');
    }
  }

  public function amendOldInDB() {
    $this->db->where('id',$this->id);
    $this->db->where('isDeleted','0');
    $query = $this->db->get('player');
    if (!$query) {
      log_message('error','Error during player amendment!');
      return false;
    }
    $tPlayer = $query->row();

    $nameId = $this->name->amendOldInDB($tPlayer->nameId);
    $ageId = $this->age->amendOldInDB($tPlayer->ageId);

    $tos = $tPlayer->skillsIds;
    $oldSkillIds = explode(',',$tos);
    $tSkills = array();
    foreach ($oldSkillIds as $skillId) {
      $tExp = explode(':',$skillId);
      $tSkills[$tExp[0]]=$tExp[1];
    };

    $skillsId = '';
    foreach ($this->skills as $skill) {
      $skillsId .= $skill->amendOldInDB($tSkills[$skill->getType()]). ",";
    };
    $skillsId = substr($skillsId, 0, -1);

    $formId = $this->form->amendOldInDB($tPlayer->formId);
    $matchReadinessId = $this->matchReadiness->amendOldInDB($tPlayer->matchReadinessId);

    $experienceId = $tPlayer->experienceId;
    $this->db->where('id',$experienceId);
    $query = $this->db->get('playerexperience');

    if ($query->row()->experience != $this->experience) {
      $this->db->set('playerId',$this->id);
      $this->db->set('experience',$this->experience);
      $query = $this->db->insert('playerexperience');
      $newExperienceId = $this->db->insert_id();

      $this->db->set('playerId', $playerId);
      $this->db->set('table','playerexperience');
      $this->db->set('oldId',$experienceId);
      $this->db->set('newId',$newExperienceId);
      $this->db->set('insertTime',date('Y-m-d H:i:s'));
      $query = $this->db->insert('playerhistory');

      $experienceId = $newExperienceId;
    }

    $loyaltyId = $tPlayer->loyaltyId;
    $this->db->where('id',$loyaltyId);
    $query = $this->db->get('playerloyalty');

    if ($query->row()->loyalty != $this->loyalty) {
      $this->db->set('playerId',$this->id);
      $this->db->set('loyalty',$this->loyalty);
      $query = $this->db->insert('playerloyalty');
      $newLoyaltyId = $this->db->insert_id();

      $this->db->set('playerId', $playerId);
      $this->db->set('table','playerloyalty');
      $this->db->set('oldId',$loyaltyId);
      $this->db->set('newId',$newLoyaltyId);
      $this->db->set('insertTime',date('Y-m-d H:i:s'));
      $query = $this->db->insert('playerhistory');

      $loyaltyId = $newLoyaltyId;
    }

    $trainingId = $this->training->amendOldInDB($tPlayer->trainingId);

    $commitmentId = NULL;
    if ($this->type=='outfielder') {
      $commitmentId = $tPlayer->commitmentId;
      $this->db->where('id',$commitmentId);
      $query = $this->db->get('playercommitment');

      if ($query->row()->commitment != $this->commitment) {
        $this->db->set('playerId',$this->id);
        $this->db->set('commitment',$this->commitment);
        $query = $this->db->insert('playercommitment');
        $newCommitmentId = $this->db->insert_id();

        $this->db->set('playerId', $playerId);
        $this->db->set('table','playercommitment');
        $this->db->set('oldId',$loyaltyId);
        $this->db->set('newId',$newLoyaltyId);
        $this->db->set('insertTime',date('Y-m-d H:i:s'));
        $query = $this->db->insert('playerhistory');

        $commitmentId = $newCommitmentId;
      }
    }

    $tos = $tPlayer->choiceIds;
    $oldChoiceIds = explode(',',$tos);
    $tChoice = array();
    foreach ($oldChoiceIds as $choiceId) {
      $tExp = explode(':',$choiceId);
      $tChoice[$tExp[0]]=$tExp[1];
    };

    $choiceIds = '';
    foreach ($this->choices as $choice) {
      $choiceIds .= $choice->amendOldInDB($tChoice[$choice->getType()]). ',';
    };
    $choiceIds = substr($choiceIds, 0, -1);

    $salaryId = $this->salary->amendOldInDB($tPlayer->salaryId);

    $revealSkillsId = $tPlayer->revealSkillsId;
    $this->db->where('id',$revealSkillsId);
    $query = $this->db->get('playerrevealskills');

    if ($query->row()->revealSkills != $this->revealSkills) {
      $this->db->set('playerId',$this->id);
      $this->db->set('revealSkills',$this->revealSkills);
      $query = $this->db->insert('playerrevealskills');
      $newRevealSkillsId = $this->db->insert_id();

      $this->db->set('playerId', $playerId);
      $this->db->set('table','playerrevealskills');
      $this->db->set('oldId',$loyaltyId);
      $this->db->set('newId',$newLoyaltyId);
      $this->db->set('insertTime',date('Y-m-d H:i:s'));
      $query = $this->db->insert('playerhistory');

      $revealSkillsId = $newRevealSkillsId;
    }

    $underEvaluationId = $tPlayer->underEvaluationId;
    $this->db->where('id',$underEvaluationId);
    $query = $this->db->get('playerunderevaluation');

    if ($query->row()->underEvaluation != $this->underEvaluation) {
      $this->db->set('playerId',$this->id);
      $this->db->set('underEvaluation',$this->underEvaluation);
      $query = $this->db->insert('playerunderevaluation');
      $newUnderEvaluationId = $this->db->insert_id();

      $this->db->set('playerId', $playerId);
      $this->db->set('table','playerunderevaluation');
      $this->db->set('oldId',$loyaltyId);
      $this->db->set('newId',$newLoyaltyId);
      $this->db->set('insertTime',date('Y-m-d H:i:s'));
      $query = $this->db->insert('playerhistory');

      $underEvaluationId = $newUnderEvaluationId;
    }
    $nationalTeamId = $this->nationalTeam->amendOldInDB($tPlayer->nationalTeamId);
    $nationalTeamProspectId = $this->nationalTeamProspect->amendOldInDB($tPlayer->nationalTeamProspectId);
    $matchesId = $this->matches->amendOldInDB($tPlayer->matchesId);

    $this->db->set('nameId',$nameId);
    $this->db->set('ageId',$nameId);
    $this->db->set('skillsIds',$skillsId);
    $this->db->set('formId',$formId);
    $this->db->set('matchReadinessId',$matchReadinessId);
    $this->db->set('experienceId',$experienceId);
    $this->db->set('loyaltyId',$loyaltyId);
    $this->db->set('trainingId',$trainingId);
    $this->db->set('commitmentId',$commitmentId);
    $this->db->set('choiceIds',$choiceIds);
    $this->db->set('salaryId',$salaryId);
    $this->db->set('revealSkillsId',$revealSkillsId);
    $this->db->set('underEvaluationId',$underEvaluationId);
    $this->db->set('nationalTeamId',$nationalTeamId);
    $this->db->set('nationalTeamProspectId',$nationalTeamProspectId);
    $this->db->set('matchesId',$matchesId);
    $this->db->where('id',$this->id);
    $query = $this->db->update('player');

    if (!$query) {
      log_message('error', 'Error during player amendment!');
    } else {
      log_message('info','Old player record ('.$this->id.') was amended in the database!');
    }
  }

  public function loadFromDB($playerId) {
    $this->db->where('id',$playerId);
    $query = $this->db->get('player');

    if (!$query || $query->num_rows()) {
      log_message('error', 'Player ('.playerId.') not found in database.');
    } else {
      $tRow = $query->row();

      $this->id = $tRow->id;

      $this->type = $tRow->type;

      $this->name->loadFromDB($tRow->nameId);
      $this->age->loadFromDB($tRow->ageId);

      $this->skills = array();
      $skillsIds = $tRow->skillsIds;
      $skillIds = explode(',', $skillsIds);
      foreach ($skillIds as $skillId) {
        $skill = new PlayerSkill();
        $tSkillId = explode(':',$skillId);
        $skill->loadfromDB($tSkillId[1]);
        array_push($this->skills,$skill);
      }

      $this->preferredFoot = $tRow->preferredFoot;

      $this->form->loadFromDB($tRow->formId);

      $this->matchReadiness->loadFromDB($tRow->matchReadinessId);

      $this->db->where('id',$tRow->experienceId);
      $query = $this->db->get('playerexperience');
      if (!$query) {
        log_message('error', 'Playerexperience not found!');
      }
      $this->experience = $query->row()->experience;

      $this->db->where('id',$tRow->loyaltyId);
      $query = $this->db->get('playerloyalty');
      if (!$query) {
        log_message('error', 'PlayerLoyalty not found!');
      }
      $this->loyalty = $query->row()->loyalty;

      $this->training->loadFromDB($tRow->trainingId);

      if ($this->type=='outfielder') {
        $this->db->where('id',$tRow->commitmentId);
        $query = $this->db->get('playercommitment');
        if (!$query) {
          log_message('error', 'Playercommitment not found!');
        }
        $this->commitment = $query->row()->commitment;
      }

      $this->choices = array();
      $choisesIds = $tRow->choiceIds;
      $choiseIds = explode(',', $choisesIds);
      foreach ($choiseIds as $choiseId) {
        $choice = new PlayerChoise();
        $tChoiseId = explode(':',$choiseId);
        $choice->loadfromDB($tChoiseId[1]);
        array_push($this->choices,$choice);
      }

      $this->salary->loadFromDB($tRow->salaryId);

      $this->purchasePrice = $tRow->purchasePrice;
      $this->joinDate = $tRow->joinDate;
      $this->nation = $tRow->nation;
      $this->homeClubId = $tRow->homeClubId;

      $this->personalities = array();
      $tRowPersonalities = $tRow->personalities;
      $tPersonalities = explode(',', $tRowPersonalities);
      array_pop($tPersonalities);
      foreach ($tPersonalities as $tPersonality) {
        array_push($this->personalities,$tPersonality);
      }

      $this->specialAbilities = array();
      $tRowSpecialAbilities = $tRow->specialAbilities;
      $tSpecialAbilities = explode("\n", $tRowSpecialAbilities);
      array_pop($tSpecialAbilities);
      foreach ($tSpecialAbilities as $tSpecialAbility) {
        array_push($this->specialAbilities,$tSpecialAbility);
      }

      $this->db->where('id',$tRow->revealSkillsId);
      $query = $this->db->get('playerrevealskills');
      if (!$query) {
        log_message('error', 'PlayerRevealSkills not found!');
      }
      $this->revealSkills = $query->row()->revealSkills;

      $this->db->where('id',$tRow->revealSkillsId);
      $query = $this->db->get('playerunderevaluation');
      if (!$query) {
        log_message('error', 'PlayerUnderEvaluation not found!');
      }
      $this->underEvaluation = $query->row()->underEvaluation;


      $this->nationalTeam->loadFromDB($tRow->nationalTeamId);
      $this->nationalTeamProspect->loadFromDB($tRow->nationalTeamProspectId);
      $this->matches->loadFromDB($tRow->matchesId);

      $this->isDeleted = $tRow->isDeleted;
    }
  }
}
?>
